package com.dr.java.day04;

/**
 * Created by rui on 2017/12/29.
 */
public class FindIndex {
    public static void main(String[] args) {
        int[] arr = {2, 4, 5, 7, 8, 19, 32, 45};
        int index = findIndex(arr, 20);
        System.out.println(index);
    }

//    折半搜索：前提是一定要有序
    private static int findIndex(int[] arr, int i) {
        int min = 0;
        int max = arr.length - 1;
        while (min < max) {
            int mid = (max + min) >> 1;
            if (arr[mid] > i) {
                max = mid - 1;//每次赋新值要让范围不断的变小，min要变大，max要变小
            } else if (arr[mid] < i) {
                min = mid + 1;
            } else {
                return mid;
            }
        }//退出循环的时候一定是min>max
        return min;
    }
}
